/*
 * Sampling.c
 *
 * Created: 26/04/2012 16:18:43
 *  Author: Dani
 */ 

#include <avr/io.h>
#define F_CPU 8000000
#include <util/delay.h>
#include <avr/interrupt.h>
#include "lcd162.h"
#include "weight_sensor_sampling.h"
#include "switch.h"
#include "uart.h"
#include "engine.h"

#define STADISTICS_SAMPLES 10000

uint16_t samples_counter = STADISTICS_SAMPLES;

void InitADC()
{
  // Internal 5 volt reference, ADLAR = 0, Input = ADC0 single ended
	ADMUX = 0b10000000;
  // ADC enable
  // ADC interrupt disabled
  // -------------ADC prescaler = 32 (=> ADC clock = 3,6864 MHz / 32 = 115 kHZ)
  ADCSRA = 0b10000110;
}

int main(void)
{
	sei();	
	LCDInit();
	LCDDispString("Ready");
	EngineInit();
	EngineControl(ENGINE_ALL,SPEED_0);
	WeightSensorInit();
	SwitchInit();
	UARTInit(9600,8);
	InitADC();
	
	//setFirstStageGain(72);
		
	while(1)
    {
		if (S3()) // Start sampling
		{
			// If previous sampling done
			if (samples_counter == STADISTICS_SAMPLES)
			{
				samples_counter = 0;
			}  
		}
		
		if (samples_counter == 0)
		{
			for (samples_counter = 0; samples_counter < STADISTICS_SAMPLES; samples_counter++)
			{
				//Start conversion
				//ADCSRA |= 1<<ADSC;
				ADCSRA |= 0b01000000;
				// Wait for conversion to finish
				// 8 us?
				while (ADCSRA & 0b01000000)
				{}
				//Send Data Read
				// 2,1 ms?
				SendInteger(ADCW);
				SendChar(',');
				if ((samples_counter % 10) == 0)
				{	
				LCDClear();
				LCDDispInteger(samples_counter);
				}				
			}			
		}
	}
	return 0;
}

ISR(S2)
{
	EngineControl(ENGINE_SERVING, SPEED_MAX);
}